package code1.backtracking;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 原题链接：https://leetcode.cn/problems/combination-sum/description/
 */
public class P39 {


    List<List<Integer>> result=new ArrayList<>();
    LinkedList<Integer> list=new LinkedList<>();
    int sum=0;

    public void backtracking(int[] candidates,int target,int last){
        if(sum>=target){
            if(sum>target) return;
            if(sum==target){
                result.add(new ArrayList<>(list));
                return;
            }
        }
        for(int i=0;i<candidates.length;i++){
            if(candidates[i]>=last){            //避免出现相同的集合
                list.add(candidates[i]);
                sum+=candidates[i];
                backtracking(candidates,target,candidates[i]);
                sum-=candidates[i];             //回溯
                list.removeLast();
            }
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtracking(candidates,target,0);
        return result;
    }
}
